<template>
  <el-dialog title="文件下载" :model-value="visible" width="600" :show-close="false" :close-on-click-modal="false">
    <div class="file-list">
      <div class="file-item" v-for="item in fileInfoList" :key="item.guid">
        <div class="icon">
          <office-icon style="font-size: 40px;" :type="item.fileType.replace('.', '')"></office-icon>
        </div>
        <div class="meta">
          <el-text class="name" truncated :title="item.fileName">
            {{ item.fileName }}
          </el-text>
          <div class="size">{{ (item.fileSize / 1024).toFixed(2) + "KB" }}</div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="buttons">
        <el-checkbox style="margin-right: 12px;" :disabled="props.fileIds.length <= 1" v-model="isZip" label="压缩下载" />
        <el-button @click="emits('close')">关闭</el-button>
        <el-button @click="onDownload" type="primary">
          下载
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ApiTree from '@/server/api-tree';
import type { FileInfoDTO } from '@/server/file/types';
import { ref, watch } from 'vue';
import OfficeIcon from '../Icon/OfficeIcon.vue';

const props = defineProps<{
  visible: boolean,
  fileIds: string[]
}>();
const isZip = ref(false);
const fileInfoList = ref<FileInfoDTO[]>([]);
const emits = defineEmits(["close", "downloaded"]);

const onDownload = () => {
  if (isZip.value) {
    // todo: 实现服务端多文件压缩成zip然后下载
    return;
  }
  // 循环下载文件列表里的文件
  fileInfoList.value.forEach((file) => {
    ApiTree.file.browserDownload(file.guid);
  })
  emits("downloaded")
}

watch(() => props.visible, async () => {
  if (props.visible && props.fileIds.length > 0) {
    const { success, data } = await ApiTree.file.getFileInfo(props.fileIds);
    if (success) {
      fileInfoList.value = data;
    }
  } else {
    fileInfoList.value = [];
  }
})
</script>
<style lang="scss" scope>
.file-list {
  display: flex;
  align-items: center;
  // justify-content: space-around;
  // width: 600px;

  .file-item {
    height: 56px;
    width: 260px;
    display: flex;
    flex-direction: row;
    box-shadow: 1px 1px 4px 4px #e2e2e2;
    padding: 8px;
    align-items: center;

    .meta {
      width: 200px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 0 4px;

      .name {
        line-height: 28px;
        font-size: 12px;
        font-weight: 600;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .size {
        font-size: 10px;
        font-weight: 600;
        text-align: right;
      }
    }

    .icon {
      width: 40px;
      height: 40px;
    }
  }
}

.buttons {
  display: flex;
  align-items: center;
  justify-content: right;
}
</style>
